package com.example.xlzx.service.impl;

import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEvent;
import com.coze.openapi.client.chat.model.ChatEventType;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.config.Consts;
import com.coze.openapi.service.service.CozeAPI;
import com.example.xlzx.entity.vo.CozeVo;
import com.example.xlzx.service.CozeService;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Collections;

@Service
@Slf4j
public class CozeServiceImpl implements CozeService {
    private final String token = "pat_zSbBgPyKY5rorUEmQqeX09oxt1o7vqsTreaCqKGv1vUkdWd6iGyux1W6AvGPCSMy";
    private final String botID = "7480874190019936271";
    public String generateResponse(CozeVo cozeVo) {
        //非流式输出
        TokenAuth authCli = new TokenAuth(token);
        // Init the Coze client through the access_token.
        CozeAPI coze = new CozeAPI.Builder()
                .baseURL(Consts.COZE_CN_BASE_URL)
                .auth(authCli)
                .readTimeout(10000)
                .build();

        // Create chat request
        CreateChatReq req = CreateChatReq.builder()
                .botID(botID)
                .userID(cozeVo.getUserId())
                .messages(Collections.singletonList(Message.buildUserQuestionText(cozeVo.getMessage())))
                .build();

        // Initiate chat and process responses
        Flowable<ChatEvent> resp = coze.chat().stream(req);
        StringBuilder result = new StringBuilder();
        resp.blockingForEach(
                event -> {
                    if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
                        result.append(event.getMessage().getContent());
                    }
                    if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) {
                        System.out.println("Token usage:" + event.getChat().getUsage().getTokenCount());
                    }
                });

        coze.shutdownExecutor();
        return result.toString();
        }
}
